package cloud.lysky.java.on.async.completable_future;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author luoly
 * @describe
 * @date 2022-08-25 9:35
 **/
public class App {
    public static void main(String[] args) {
        Shop shop = new Shop("Best Shop");
        long l = System.nanoTime();
        Future<Double> futurePrice = shop.getPriceAsyncUp("My favorite product");
        long invocationTime = (System.nanoTime()-l) / 1_000_000;
        System.out.println("Invocation returned after " + invocationTime + "msecs");

        //执行更多任务比如查询其它商店
        doSomethingElse();

        try {
            double price = futurePrice.get();//从Future对象中读取价格，如果价格未知,会发生阻塞
            System.out.println("price is " + price);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        long retrievalTime = (System.nanoTime() - l) / 1_000_000;
        System.out.println("Price returned after " + retrievalTime + "msecs");
    }

    private static void doSomethingElse() {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}